package com.sdyc.ndmp.cls.server;

import akka.actor.ActorRef;
import akka.actor.ReceiveTimeout;
import akka.actor.UntypedActor;
import com.google.common.collect.ImmutableMap;
import com.sdyc.ndmp.cls.dtd.Condition;
import com.sdyc.ndmp.cls.dtd.DataSentence;
import com.sdyc.ndmp.cls.dtd.KeywordCondition;
import com.sdyc.ndmp.cls.dtd.Sentence;
import com.sdyc.ndmp.cls.engine.Data720Engine;
import com.sdyc.ndmp.cls.engine.SenteceKeywordEngine;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import scala.concurrent.duration.Duration;

import java.util.Map;

/**
 * <pre>
 * Created with IntelliJ IDEA.
 * User: zachary
 * Date: 2015/11/18
 * Time: 14:25
 * </pre>
 *
 * @author zachary
 */
public class SentenceKeywordActor extends UntypedActor {


    protected static Log log = LogFactory.getLog(SentenceKeywordActor.class);


    protected final Data720Engine engine;

    protected volatile  long  numCount = 0L;


    protected final String clientId;


    public SentenceKeywordActor(Map<String, Object> param) {
        log.info("params " + param);
        engine = new Data720Engine();
        this.clientId = String.valueOf(param.get("clientId"));
    }


    @Override
    public void preStart() throws Exception {
        super.preStart();
    }

    @Override
    public void onReceive(Object message) throws Exception {
        if(message instanceof Sentence) {
            numCount++;
            if(numCount % 1000 == 0) {
                log.info(clientId + " Rpc numCount：" + numCount);
            }
            //将处理结果返回给客户端, 需要返回 Map 类型的结果
            getSender().tell(engine.rule((Sentence)message), ActorRef.noSender());
            //log.info("server 处理完数据:" + message);
        } else if(message instanceof KeywordCondition) {
            numCount = 1L;
            //因为 KeyWordKeywordCondition 调用的次数少, 因此后匹配, 提高处理性能
            engine.init((Condition) message);
            ImmutableMap<String, Object> res = ImmutableMap.<String, Object>of("success", true, "message", "init success!");
            getSender().tell(res, ActorRef.noSender());
            log.info(res);
        }else if (message instanceof ReceiveTimeout) {
            log.info("接收消息超时");
            getContext().setReceiveTimeout(Duration.Undefined());
        } else {
            unhandled(message);
        }



    }

}
